# -*-coding:utf-8 -*-
#!/usr/bin/env python

import cv2
import os
import numpy as np
from math import atan
from scipy import ndimage


img = cv2.imread('rotr2.png')
cv2.imshow('src',img)

'''
#产生旋转图
for i in range(3):
    src = ndimage.rotate(img, (i+1)*(-10))
    cv2.imwrite("rot%d.png"%i, src)
'''
#gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#cv2.imshow('gray',gray)

#倾斜校正
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #灰度化

(T,thresh) = cv2.threshold(gray, 230, 255, cv2.THRESH_BINARY)#阈值化

cv2.imshow('thresh',thresh)

#膨胀
kel = np.ones(50)
dilate = cv2.dilate(thresh,kel)
cv2.imshow('dilate',dilate)

#轮廓
image, contours, hier = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.imshow('dilate',dilate)


#寻找最大轮廓
area=0
cnt = contours[0]
for c in contours:
    tmp_area = cv2.contourArea(c)
    if tmp_area>=area:
        area = tmp_area
        cnt = c

#做出外接矩形
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
con = cv2.drawContours(img, [box], 0,(0,255,0),2)
cv2.imshow("con",img)

if rect[1][0]<rect[1][1] and rect[2]!=-90:
    angle = rect[2]
else:
    angle = rect[2]+90
print('angle%f'%angle)
img = ndimage.rotate(thresh, angle)





    
